/////////////////////////////////////////////////////////////////////////////
// Original code from libhdfs3. Copyright (c) 2013 - 2014, Pivotal Inc.
// All rights reserved. Author: Zhanwei Wang
/////////////////////////////////////////////////////////////////////////////
//  Modifications by Kumo Inc.
// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//



#include <kmhdfs/server/namenode_info.h>
#include <turbo/strings/ascii.h>
#include <turbo/strings/str_split.h>
#include <turbo/strings/str_cat.h>
#include <kmhdfs/common/xml_config.h>

#include <string>
#include <vector>

namespace Hdfs {
    NamenodeInfo::NamenodeInfo() {
    }

    const char *DFS_NAMESERVICES = "dfs.nameservices";
    const char *DFS_NAMENODE_HA = "dfs.ha.namenodes";
    const char *DFS_NAMENODE_RPC_ADDRESS_KEY = "dfs.namenode.rpc-address";
    const char *DFS_NAMENODE_HTTP_ADDRESS_KEY = "dfs.namenode.http-address";

    std::vector<NamenodeInfo> NamenodeInfo::GetHANamenodeInfo(
        const std::string &service, const Config &conf) {
        std::vector<NamenodeInfo> retval;
        auto strNameNodes = turbo::trim_all(
            conf.getString(std::string(DFS_NAMENODE_HA) + "." + service));
        std::vector<std::string> nns = turbo::str_split(strNameNodes, ",");
        retval.resize(nns.size());

        for (size_t i = 0; i < nns.size(); ++i) {
            auto dfsRpcAddress = turbo::str_cat(turbo::trim_all(DFS_NAMENODE_RPC_ADDRESS_KEY), ".", service, "."
                                                , turbo::trim_all(nns[i]));
            auto dfsHttpAddress = turbo::str_cat(
                turbo::trim_all(DFS_NAMENODE_HTTP_ADDRESS_KEY), ".", service, "."
                , turbo::trim_all(nns[i]));
            retval[i].setRpcAddr(std::string(turbo::trim_all(conf.getString(dfsRpcAddress, ""))));
            retval[i].setHttpAddr(std::string(turbo::trim_all(conf.getString(dfsHttpAddress, ""))));
        }

        return retval;
    }
}
